package com.example.androidstudy.ui.demo.paging3

import android.graphics.Rect
import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.paging.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.androidstudy.R
import com.example.androidstudy.databinding.FragmentPaging3DemoBinding
import com.example.androidstudy.extend.logE
import com.example.androidstudy.ui.BaseFragment
import com.example.androidstudy.ui.demo.recyclerview.NumberInfo
import com.google.android.material.divider.MaterialDividerItemDecoration
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import javax.inject.Inject

@AndroidEntryPoint
@ExperimentalPagingApi
class Paging3DemoFragment :
    BaseFragment<FragmentPaging3DemoBinding>(R.layout.fragment_paging3_demo) {
    val adaptet = Paging3AdapterData()

    @Inject
    lateinit var db: NumberInfoDb

    @Inject
    lateinit var pager: Pager<Int, NumberInfo>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun FragmentPaging3DemoBinding.initView() {
        rcDatas.layoutManager = LinearLayoutManager(context)
        rcDatas.addItemDecoration(
            MaterialDividerItemDecoration(
                rcDatas.context,
                (rcDatas.layoutManager as LinearLayoutManager).orientation
            ).apply {
                dividerColor = resources.getColor(R.color.design_default_color_error)
                dividerThickness = 20
                dividerInsetStart = 50
                dividerInsetEnd = 40
            }
        )
        rcDatas.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                outRect.set(200, 0, 20, 50)
            }
        })
        rcDatas.adapter = adaptet
        lifecycleScope.launchWhenCreated {

            val dataFlow = pager.flow.cachedIn(lifecycleScope)
            dataFlow.collectLatest {
                adaptet.submitData(it)
            }
        }
        adaptet.loadStateFlow.onEach {
            it.toString().logE()
            srlDatas.isRefreshing = it.refresh is LoadState.Loading
        }.launchIn(lifecycleScope)

        srlDatas.setOnRefreshListener {
            adaptet.refresh()
        }
    }
}

